// 类：服务中项目查询页面逻辑（卡片展示、区域筛选、搜索）
// 方法：初始化、渲染区域按钮、渲染项目卡片、搜索过滤

layui.use(['layer', 'form', 'dropdown'], function () {
    var layer = layui.layer;
    var form = layui.form;
    var dropdown = layui.dropdown;

    // 初始化静态数据（仅前端示例）
    var staticProjects = [
        { id: 1, projectName: '智慧城市建设项目', projectShortName: '智慧城市', region: '华东区域', serviceArea: '上海市浦东新区', projectMemberCount: 25, contractName: '智慧城市一期建设合同', createdAt: '2024-08-01', isWithdrawn: false },
        { id: 2, projectName: '工业园区管理系统', projectShortName: '工业园', region: '华东区域', serviceArea: '江苏省苏州市', projectMemberCount: 18, contractName: '工业园区数字化管理合同', createdAt: '2024-08-05', isWithdrawn: false },
        { id: 3, projectName: '智慧交通平台', projectShortName: '智慧交通', region: '华南区域', serviceArea: '广东省深圳市', projectMemberCount: 32, contractName: '智慧交通系统建设合同', createdAt: '2024-08-12', isWithdrawn: true },
        { id: 4, projectName: '数据中心建设', projectShortName: '数据中心', region: '华北区域', serviceArea: '北京市海淀区', projectMemberCount: 45, contractName: '数据中心基础设施合同', createdAt: '2024-09-01', isWithdrawn: false },
        { id: 5, projectName: '智慧医疗系统', projectShortName: '智慧医疗', region: '华中区域', serviceArea: '湖北省武汉市', projectMemberCount: 28, contractName: '智慧医疗平台建设合同', createdAt: '2024-09-05', isWithdrawn: true },
        { id: 6, projectName: '智慧教育平台', projectShortName: '智慧教育', region: '西南区域', serviceArea: '四川省成都市', projectMemberCount: 22, contractName: '智慧教育系统合同', createdAt: '2024-09-10', isWithdrawn: false },
        { id: 7, projectName: '智慧农业项目', projectShortName: '智慧农业', region: '西北区域', serviceArea: '陕西省西安市', projectMemberCount: 15, contractName: '智慧农业平台合同', createdAt: '2024-09-15', isWithdrawn: false },
        { id: 8, projectName: '智慧物流系统', projectShortName: '智慧物流', region: '东北区域', serviceArea: '辽宁省沈阳市', projectMemberCount: 35, contractName: '智慧物流平台建设合同', createdAt: '2024-09-20', isWithdrawn: true },
    ];

    var currentRegion = ''; // 当前选中的区域
    var currentWithdraw = ''; // 当前选中的撤场状态
    var filteredProjects = [...staticProjects]; // 过滤后的项目列表

    // 初始化区域筛选下拉菜单
    function initRegionFilter() {
        // 计算各区域的项目数量
        var regionCounts = {};
        staticProjects.forEach(function(project) {
            regionCounts[project.region] = (regionCounts[project.region] || 0) + 1;
        });
        
        // 渲染 dropdown
        dropdown.render({
            elem: '#regionDropdown',
            data: [
                {
                    title: '全部区域 (' + staticProjects.length + ')',
                    id: ''
                },
                {type: '-'}, // 分割线
                {
                    title: '华东区域 (' + (regionCounts['华东区域'] || 0) + ')',
                    id: '华东区域'
                },
                {
                    title: '华南区域 (' + (regionCounts['华南区域'] || 0) + ')',
                    id: '华南区域'
                },
                {
                    title: '华北区域 (' + (regionCounts['华北区域'] || 0) + ')',
                    id: '华北区域'
                },
                {
                    title: '华中区域 (' + (regionCounts['华中区域'] || 0) + ')',
                    id: '华中区域'
                },
                {
                    title: '西南区域 (' + (regionCounts['西南区域'] || 0) + ')',
                    id: '西南区域'
                },
                {
                    title: '西北区域 (' + (regionCounts['西北区域'] || 0) + ')',
                    id: '西北区域'
                },
                {
                    title: '东北区域 (' + (regionCounts['东北区域'] || 0) + ')',
                    id: '东北区域'
                }
            ],
            click: function(obj) {
                currentRegion = obj.id;
                // 更新显示文本
                var displayText = obj.title;
                document.getElementById('regionDisplay').textContent = displayText;
                // 过滤和渲染项目
                filterAndRenderProjects();
            }
        });
    }

    // 初始化撤场状态筛选下拉菜单
    function initWithdrawFilter() {
        // 计算各撤场状态的项目数量
        var withdrawCounts = {
            'false': 0, // 未撤场
            'true': 0   // 已撤场
        };
        staticProjects.forEach(function(project) {
            if (project.isWithdrawn) {
                withdrawCounts['true']++;
            } else {
                withdrawCounts['false']++;
            }
        });
        
        // 渲染 dropdown
        dropdown.render({
            elem: '#withdrawDropdown',
            data: [
                {
                    title: '全部 (' + staticProjects.length + ')',
                    id: ''
                },
                {type: '-'}, // 分割线
                {
                    title: '否 (' + withdrawCounts['false'] + ')',
                    id: 'false'
                },
                {
                    title: '是 (' + withdrawCounts['true'] + ')',
                    id: 'true'
                }
            ],
            click: function(obj) {
                currentWithdraw = obj.id;
                // 更新显示文本
                var displayText = obj.title;
                document.getElementById('withdrawDisplay').textContent = displayText;
                // 过滤和渲染项目
                filterAndRenderProjects();
            }
        });
    }

    // 渲染项目卡片
    function renderProjectCards(projects) {
        var cardsHtml = '';
        
        if (projects.length === 0) {
            cardsHtml = '<div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #999;">暂无项目数据</div>';
        } else {
            projects.forEach(function(project) {
                cardsHtml += `
                    <div class="project-card">
                        <div class="project-header">
                            <div>
                                <div class="project-title">${project.projectName}</div>
                                <div class="project-short-name">${project.projectShortName}</div>
                            </div>
                            <div class="project-actions">
                                <button class="layui-btn layui-btn-sm" onclick="editProject(${project.id})">编辑</button>
                                <button class="layui-btn layui-btn-sm layui-btn-warm" onclick="withdrawProject(${project.id})">撤场</button>
                            </div>
                        </div>
                        <div class="project-info">
                            <div class="info-row">
                                <span class="info-label">所属区域：</span>
                                <span class="info-value">${project.region}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">服务区域：</span>
                                <span class="info-value">${project.serviceArea}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">项目人数：</span>
                                <span class="info-value">${project.projectMemberCount}人</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">合同名称：</span>
                                <span class="info-value">${project.contractName}</span>
                            </div>
                        </div>
                        <div class="project-footer">
                            <span class="project-status ${project.isWithdrawn ? 'withdrawn' : 'serving'}">${project.isWithdrawn ? '已撤场' : '服务中'}</span>
                            <span style="color: #999; font-size: 12px;">创建时间：${project.createdAt}</span>
                        </div>
                    </div>
                `;
            });
        }
        
        document.getElementById('projectCards').innerHTML = cardsHtml;
    }

    // 过滤和渲染项目
    function filterAndRenderProjects() {
        var searchValue = document.getElementById('searchInput').value.toLowerCase();
        
        // 根据区域、撤场状态和搜索条件过滤
        filteredProjects = staticProjects.filter(function(project) {
            var matchRegion = !currentRegion || project.region === currentRegion;
            var matchWithdraw = currentWithdraw === '' || project.isWithdrawn.toString() === currentWithdraw;
            var matchSearch = !searchValue || 
                project.projectName.toLowerCase().includes(searchValue) ||
                project.contractName.toLowerCase().includes(searchValue);
            
            return matchRegion && matchWithdraw && matchSearch;
        });
        
        renderProjectCards(filteredProjects);
    }

    // 通用弹窗打开方法（按钮参数化）
    var openLayer = function (options) {
        var idx = layer.open({
            type: 1,
            title: options.title || '弹窗',
            area: options.area || '600px',
            shadeClose: true,
            content: options.content,
            btn: options.btn || ['确定', '取消'],
            yes: function (index, layero) {
                if (typeof options.onYes === 'function') {
                    options.onYes(index, layero);
                } else {
                    layer.close(index);
                }
            },
            btn2: function (index, layero) {
                if (typeof options.onBtn2 === 'function') {
                    return options.onBtn2(index, layero);
                }
                // 返回 undefined 走默认关闭
            },
            end: function () {
                if (typeof options.onEnd === 'function') {
                    options.onEnd();
                }
            },
            success: function () {
                if (typeof options.onSuccess === 'function') {
                    options.onSuccess();
                }
            }
        });
        return idx;
    };

    // 新增/编辑项目（使用参数化按钮）
    var openProjectForm = function (title, data, btns) {
        return openLayer({
            title: title || '添加项目',
            area: '600px',
            content: document.getElementById('tplProjectForm').innerHTML,
            btn: btns && btns.length ? btns : ['保存', '取消'],
            onSuccess: function () {
                if (data) {
                    form.val('projectForm', data);
                }
            },
            onYes: function (index) {
                // 统一提交拦截（静态示例）
                var formData = form.val('projectForm');
                // 这里只做前端校验提示
                if (!formData.projectName || !formData.region) {
                    layer.msg('请完善必填信息');
                    return;
                }
                layer.msg('保存成功（静态示例）');
                layer.close(index);
            },
            onBtn2: function () { /* 默认关闭 */ }
        });
    };

    // 事件：搜索
    var searchBtn = document.getElementById('btnSearch');
    if (searchBtn) {
        searchBtn.addEventListener('click', filterAndRenderProjects);
    }

    // 事件：重置
    var resetBtn = document.getElementById('btnReset');
    if (resetBtn) {
        resetBtn.addEventListener('click', function () {
            document.getElementById('searchInput').value = '';
            document.getElementById('regionDisplay').textContent = '全部区域 (' + staticProjects.length + ')';
            document.getElementById('withdrawDisplay').textContent = '全部 (' + staticProjects.length + ')';
            currentRegion = '';
            currentWithdraw = '';
            filterAndRenderProjects();
            layer.msg('已重置搜索条件', { icon: 1 });
        });
    }

    // 事件：添加项目
    var addBtn = document.getElementById('btnAddProject');
    if (addBtn) {
        addBtn.addEventListener('click', function () { 
            // 跳转到项目编辑页面（新增模式）
            window.location.href = './project_edit.html';
        });
    }

    // 搜索框回车事件
    var searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                filterAndRenderProjects();
            }
        });
    }

    // 编辑项目（全局函数）
    window.editProject = function(projectId) {
        // 跳转到项目编辑页面（编辑模式）
        window.location.href = './project_edit.html?id=' + projectId;
    };

    // 撤场项目（全局函数）
    window.withdrawProject = function(projectId) {
        var project = staticProjects.find(function(p) { return p.id === projectId; });
        if (project) {
            layer.confirm(`确认撤场项目"${project.projectName}"？`, { icon: 3, title: '撤场确认' }, function (index) {
                layer.close(index);
                layer.msg('项目撤场成功（静态示例）', { icon: 1 });
            });
        }
    };

    // 初始化页面
    function initPage() {
        initRegionFilter();
        filterAndRenderProjects();
        initWithdrawFilter();
    }

    // 页面加载完成后初始化
    initPage();
});
